package com.ljk.studywebsocket.config3;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
// sockjs 需要前端注册两个地址,第一个是服务地址(在config里),第二个是监听的地址,在本controller中定义的地址,设置在stompClient.subscribe方法内
/**
 * @author ljk
 * @since 2023-01-10 20:52
 */
@RestController
public class WebsocketController {
    @Autowired
    private SimpMessagingTemplate template;


    @MessageMapping("/sendToAll")
    @SendTo("/topic")
    public String sendToAll(String msg) {
        return msg;
    }
    /**
     * 同上方一样的效果
     */
    @GetMapping("/sendToAllByTemplate")
    @MessageMapping("/sendToAllByTemplate")
    public void sendToAllByTemplate(String msg) {
        template.convertAndSend("/topic", msg);
    }


    @MessageMapping("/sendToUser")
    public void sendToUser(@RequestParam Map<String, String> param) {
        String userId = param.get("userId");
        String msg = param.get("msg");
        template.convertAndSendToUser(userId,"/topic", msg);
    }

    /**
     * 同上方一样的效果
     */
    @MessageMapping("/sendToUserByTemplate")
    @GetMapping("/sendToUserByTemplate")
    public void sendToUserByTemplate(@RequestParam Map<String, String> param) {
        String userId = param.get("toUserId");
        String msg = param.get("msg");
        template.convertAndSendToUser(userId, "/topic", msg);
    }
}
